\section{Code for problem 2}
\label{code2}
\small
\begin{verbatim}
# This function generates a sample of size N of a Pois(1) random variable.
generatePoisson <- function(N)
{
  # This is the density for a random variable Y=X+1 where X is a poisson random with lambda=1.
  Ydensity <- function(k)
  {
    return(exp(-1) / factorial(k-1))
  }

  # We notice that eta_1 is alway 1 and therefor we begin with eta_2 and set eta=1.
  etas <- rep(1, N)
  k <- 2

  # We begin by generating N Unif(0,1) variables.
  xis <- runif(N)

  # We need to remember the sum of the f(1)+...+f(k-1). This is zero for k = 1.
  densitySum <- 0

  # Helper variable.
  continue <- 1

  while(continue > 0)
  {
    # We update the density sum.
    densitySum <- densitySum + Ydensity(k - 1)

    # We calculate the additions.
    additions <- (xis + 1 - densitySum) >= 1

    # we update the eta's.
    etas <- etas + additions

    # we update the k.
    k <- k + 1

    # We continue if there has been any additions in the last loop.
    continue <- sum(additions)
  }

  # We have generated a sample for Y=X+1 so we subtract 1 to get a sample for X.
  etas <- etas - 1

  return(etas)
}

# The size of the sample that we want to generate.
N <- 10000

sample <- generatePoisson(N)

# Now we calculate the mean and the variance to see if they are 1 as they should be.
mean(sample)
var(sample)

# To check that we have actually generated random poisson variabled we plot the histogram 
# of our sample above the histogram of random sample of a poisson variable.
par(mfrow = c(2, 1))
hist(sample)
hist(rpois(N, 1))

# To further check that we have actually generated random poisson variabled we want to do a qq-plot, 
# but in order to do that with discrete variables we need to add a bit of random noize.
par(mfrow = c(1, 1))
qqplot(sample + rnorm(N, 0, 0.2), rpois(N, 1) + rnorm(N, 0, 0.2))

# We add the correct line to the qq-plot.
abline(0,1)
\end{verbatim}

\newpage